"""
Tree-sitter演示脚本
演示如何使用Tree-sitter分析当前计算器项目
"""

import os
import sys
from pathlib import Path
import json

# 添加当前目录到Python路径
current_dir = Path(__file__).parent
sys.path.insert(0, str(current_dir))

from tree_sitter_analyzer import TreeSitterCLI
from project_analyzer import ProjectAnalyzer


def demo_basic_analysis():
    """演示基本项目分析"""
    print("=== Tree-sitter 基本项目分析演示 ===")
    
    # 获取当前项目路径
    project_path = str(current_dir)
    print(f"分析项目路径: {project_path}")
    
    # 创建分析器
    analyzer = ProjectAnalyzer(
        project_path=project_path,
        file_patterns=["*.py"],
        exclude_patterns=["__pycache__/*", "*.pyc"],
        max_workers=2
    )
    
    def progress_callback(message: str, progress: float):
        print(f"  {message} ({progress:.1f}%)")
    
    try:
        # 执行分析
        print("\\n开始分析...")
        summary = analyzer.analyze_project(progress_callback)
        
        # 显示结果
        print("\\n=== 分析结果 ===")
        project_info = summary.get("project_info", {})
        stats = summary.get("symbol_statistics", {})
        
        print(f"分析的文件数量: {project_info.get('files_analyzed', 0)}")
        print(f"分析耗时: {project_info.get('analysis_time', 0):.2f} 秒")
        print(f"总符号数: {stats.get('total_symbols', 0)}")
        
        symbols_by_type = stats.get('symbols_by_type', {})
        for symbol_type, count in symbols_by_type.items():
            print(f"  {symbol_type}: {count}")
        
        return analyzer
        
    except Exception as e:
        print(f"分析失败: {e}")
        import traceback
        traceback.print_exc()
        return None


def demo_symbol_queries(analyzer: ProjectAnalyzer):
    """演示符号查询功能"""
    print("\\n\\n=== 符号查询演示 ===")
    
    # 查询所有类
    classes = analyzer.query_symbols(symbol_type="class")
    print(f"\\n找到 {len(classes)} 个类:")
    for cls in classes:
        relative_path = Path(cls.file_path).relative_to(analyzer.project_path)
        print(f"  {cls.name} in {relative_path}:{cls.definition_range.start.line if cls.definition_range else 'N/A'}")
        
        # 显示类的方法
        if cls.children:
            print(f"    方法 ({len(cls.children)}):")
            for method in cls.children[:5]:  # 只显示前5个方法
                print(f"      - {method.name}")
    
    # 查询所有函数
    functions = analyzer.query_symbols(symbol_type="function")
    print(f"\\n找到 {len(functions)} 个函数:")
    for func in functions[:10]:  # 只显示前10个函数
        relative_path = Path(func.file_path).relative_to(analyzer.project_path)
        print(f"  {func.name} in {relative_path}:{func.definition_range.start.line if func.definition_range else 'N/A'}")
    
    # 查询特定符号
    calc_symbols = analyzer.query_symbols(name="Calculator")
    print(f"\\n查询 'Calculator' 符号，找到 {len(calc_symbols)} 个:")
    for symbol in calc_symbols:
        relative_path = Path(symbol.file_path).relative_to(analyzer.project_path)
        print(f"  {symbol.name} ({symbol.type}) in {relative_path}")


def demo_reference_analysis(analyzer: ProjectAnalyzer):
    """演示引用分析功能"""
    print("\\n\\n=== 引用分析演示 ===")
    
    # 查找Calculator类的引用
    calc_refs = analyzer.find_references("Calculator")
    print(f"\\n'Calculator' 的引用 ({len(calc_refs)}):")
    for ref in calc_refs[:10]:  # 只显示前10个引用
        print(f"  {ref['file']}:{ref['line']}:{ref['column']}")
    
    # 查找其他常见符号的引用
    common_symbols = ["add", "subtract", "multiply", "divide"]
    for symbol_name in common_symbols:
        refs = analyzer.find_references(symbol_name)
        if refs:
            print(f"\\n'{symbol_name}' 的引用 ({len(refs)}):")
            for ref in refs[:5]:  # 只显示前5个引用
                print(f"  {ref['file']}:{ref['line']}:{ref['column']}")


def demo_ast_analysis(analyzer: ProjectAnalyzer):
    """演示AST分析功能"""
    print("\\n\\n=== AST结构演示 ===")
    
    # 选择一个文件进行AST分析
    calculator_files = [fp for fp in analyzer.file_analyses.keys() 
                       if "calculator_core.py" in fp]
    
    if calculator_files:
        file_path = calculator_files[0]
        print(f"\\n分析文件: {Path(file_path).name}")
        
        ast_structure = analyzer.get_file_ast(file_path)
        if ast_structure and "error" not in ast_structure:
            print("\\nAST结构 (部分):")
            print_ast_tree(ast_structure, max_depth=2)
        else:
            print(f"无法获取AST: {ast_structure}")


def print_ast_tree(node, indent=0, max_depth=3):
    """打印AST树结构（限制深度）"""
    if indent > max_depth:
        return
    
    prefix = "  " * indent
    node_type = node.get("type", "unknown")
    node_text = node.get("text", "")[:30]  # 限制显示长度
    
    print(f"{prefix}{node_type}: {repr(node_text)}")
    
    children = node.get("children", [])
    if children and indent < max_depth:
        for child in children[:3]:  # 只显示前3个子节点
            print_ast_tree(child, indent + 1, max_depth)
        if len(children) > 3:
            print(f"{prefix}  ... ({len(children) - 3} more children)")


def demo_code_metrics(analyzer: ProjectAnalyzer):
    """演示代码度量功能"""
    print("\\n\\n=== 代码度量演示 ===")
    
    if analyzer.code_metrics:
        try:
            # 计算复杂度指标
            metrics = analyzer.code_metrics.calculate_complexity_metrics()
            print("\\n复杂度指标:")
            
            size_metrics = metrics.get("size_metrics", {})
            for file_path, file_metrics in list(size_metrics.items())[:5]:  # 只显示前5个文件
                relative_path = Path(file_path).relative_to(analyzer.project_path)
                print(f"  {relative_path}:")
                print(f"    函数数: {file_metrics.get('functions_count', 0)}")
                print(f"    类数: {file_metrics.get('classes_count', 0)}")
                print(f"    总符号数: {file_metrics.get('total_symbols', 0)}")
            
            # 获取代码热点
            hotspots = analyzer.code_metrics.get_hotspots()
            print(f"\\n代码热点 (前10个):")
            for i, hotspot in enumerate(hotspots[:10], 1):
                print(f"  {i:2d}. {hotspot['symbol']} ({hotspot['type']}) - {hotspot['reference_count']} 引用")
        
        except Exception as e:
            print(f"计算度量时出错: {e}")
    else:
        print("代码度量功能不可用")


def demo_save_results(analyzer: ProjectAnalyzer):
    """演示保存结果功能"""
    print("\\n\\n=== 保存结果演示 ===")
    
    try:
        # 保存JSON格式
        json_output = current_dir / "analysis_result.json"
        analyzer.save_results(str(json_output), "json")
        print(f"JSON结果已保存到: {json_output}")
        
        # 保存HTML格式
        html_output = current_dir / "analysis_report.html"
        analyzer.save_results(str(html_output), "html")
        print(f"HTML报告已保存到: {html_output}")
        
        print("\\n可以打开HTML文件查看详细的分析报告!")
        
    except Exception as e:
        print(f"保存结果时出错: {e}")


def demo_cli_usage():
    """演示命令行用法"""
    print("\\n\\n=== 命令行用法演示 ===")
    
    print("\\n以下是一些有用的命令行示例:")
    project_path = str(current_dir)
    
    print(f"\\n1. 分析整个项目:")
    print(f"   python tree_sitter_analyzer.py analyze --project-path {project_path}")
    
    print(f"\\n2. 查询Calculator类:")
    print(f"   python tree_sitter_analyzer.py query --project-path {project_path} --name Calculator")
    
    print(f"\\n3. 查找add函数的引用:")
    print(f"   python tree_sitter_analyzer.py references --project-path {project_path} --symbol add")
    
    print(f"\\n4. 显示文件AST:")
    print(f"   python tree_sitter_analyzer.py ast --file-path calculator_core.py")
    
    print(f"\\n5. 显示代码度量:")
    print(f"   python tree_sitter_analyzer.py metrics --project-path {project_path}")


def main():
    """主演示函数"""
    print("🌳 Tree-sitter 项目级语法树分析系统演示")
    print("=" * 60)
    
    try:
        # 基本分析演示
        analyzer = demo_basic_analysis()
        
        if analyzer:
            # 符号查询演示
            demo_symbol_queries(analyzer)
            
            # 引用分析演示
            demo_reference_analysis(analyzer)
            
            # AST分析演示
            demo_ast_analysis(analyzer)
            
            # 代码度量演示
            demo_code_metrics(analyzer)
            
            # 保存结果演示
            demo_save_results(analyzer)
            
            # 命令行用法演示
            demo_cli_usage()
            
            print("\\n\\n🎉 演示完成!")
            print("\\n你现在可以:")
            print("1. 查看生成的 analysis_report.html 文件")
            print("2. 使用命令行工具分析其他项目")
            print("3. 根据需要修改和扩展分析功能")
        
    except Exception as e:
        print(f"\\n演示过程中出错: {e}")
        import traceback
        traceback.print_exc()


if __name__ == "__main__":
    # 检查依赖
    try:
        import tree_sitter
        from tree_sitter_python import language
    except ImportError as e:
        print(f"缺少依赖: {e}")
        print("\\n请安装所需依赖:")
        print("pip install tree-sitter tree-sitter-python")
        sys.exit(1)
    
    main()